package ${projectDomain}.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import ${projectDomain}.cache.RedisAdapter;
import ${projectDomain}.config.RequestConfig;
import ${projectDomain}.pojo.vo.ResponseBody;
import com.unswift.exception.CoreException;
import com.unswift.utils.ExceptionUtils;

import reactor.core.publisher.Mono;

@Component
@Api(value="权限拦截器", author = "unswift", date = "2023-08-13", version = "1.0.0")
public class AuthorizationFilter extends CloudFilter implements GlobalFilter, Ordered{

	@Autowired
	@ApiField("请求yml配置")
	private RequestConfig requestConfig;
	
	@Autowired
	@ApiField("redis业务处理类")
	private RedisAdapter redisAdapter;
	
	@Override
	@ApiMethod(value="获取filter的执行顺序，值越小，越靠前，此值最好不要大于1，否则的话取到的path会没有路由", returns = @ApiField("执行顺序"))
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE+2;
	}

	@Override
	@ApiMethod(value="拦截器执行方法，在此方法中拦截签名", params = {@ApiField("http请求的封装，提供对HTTP的访问请求和响应"), @ApiField("委托")})
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		try {
			ServerHttpRequest request = exchange.getRequest();
			String path=request.getPath().value();
			if(requestConfig.matchAuthWhite(path)) {
				return chain.filter(exchange);
			}
			logger.error("auth："+path);
	        HttpHeaders headers = request.getHeaders();
	        String token=headers.getFirst(tokenConfig.getKeyName());
	        ExceptionUtils.empty(token, "login.failure");
	        token=getUserToken(token);
	        boolean exists=redisAdapter.exists(token);
	        ExceptionUtils.falseException(exists, "login.failure");
	        redisAdapter.expire(token, tokenConfig.getExpireInt());//刷新token
			return chain.filter(exchange);
		} catch (CoreException e) {
			e.printStackTrace();
			return toJson(exchange, ResponseBody.error(e.getCode(), e.getMessage()));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			return toJson(exchange, ResponseBody.error("unknown.error", String.format(ExceptionUtils.getMessage("unknown.error"), e.getMessage())));
		}
	}

	
}
